﻿using YeqianFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using YeqianFramework.core;
using YeqianFramework.common;
using Assets.Scripts.config;
using Assets.Scripts.events;
using Assets.Scripts.UI;
using Assets.Scripts.Manager;

namespace Assets.Scripts
{
	/// <summary>
	/// 挂载在行星上
	/// </summary>
	public class Planet : Star
	{
		public PlanetData data;

		public float temperature;
		public float QT;
		protected override void InitStarData()
		{
			data = TheThreeBodyGameManager.Current.PlanetData;
			transform.position = data.Position;
			transform.localScale = Vector3.one * data.Scale;

			m_Rigidbody.mass = data.Mass;

			speed = data.AwakeSpeedFactor == 0 ? TheThreeBodyGameManager.Current.GameConfig.AwakeSpeedFactor : data.AwakeSpeedFactor;

			temperature = data.AwakeTemperature;

			ScalePower2 = Mathf.Pow(data.Scale, 2);
			PiTime4 = 4 * Mathf.PI;
		}

		protected override void FixedUpdate()
		{
			base.FixedUpdate();

			float dT1 = 0;
			//CalculateTemperature();
			for (int i = 0; i < rigidbodies.Count; i++)
			{
				if (!rigidbodies[i].gameObject.activeInHierarchy) continue;
				dT1 += CalculateTemperature(rigidbodies[i].GetComponent<FixedStar>().data.Luminosity, oneDivideDistancePower2[i]);
			}
			temperature += (dT1 - QT) * Time.deltaTime;
			UIDebugeField.Current.UpdateMessage(debugKey, string.Format(
@"表面温度：{0} K
散热速率：{1} K/s
加热速率：{2} K/s
dt : {3}
"
, temperature.ToString(), QT.ToString(), dT1.ToString(), Time.deltaTime));
		}

		private float CalculateTemperature(float luminosity, float oneDivideDistancePower2)
		{
			CalculateQT();
			//MessageCenter.Current.SendMyMessage(GameEvent.PlanetTemperatureUpdate, new KeyValuePair(gameObject.name, new float[] { temperature, QT }));
			return luminosity * oneDivideDistancePower2;
		}

		/// <summary>
		/// 半径的平方
		/// </summary>
		private float ScalePower2;
		/// <summary>
		/// 4π
		/// </summary>
		private float PiTime4;

		/// <summary>
		/// 计算散热速率
		/// </summary>
		private void CalculateQT()
		{
			QT = data.CoolingDownSpeed * PiTime4 * ScalePower2 * temperature;
		}

		private string debugKey = "行星数据";
		private void OnEnable()
		{
			UIDebugeField.Current.AddMessage(debugKey, "");
		}
		private void OnDestroy()
		{
			UIDebugeField.Current.RemoveMessage(debugKey);
		}

		protected override void OnCollisionEnter(Collision collision)
		{
			MessageCenter.Current.SendMyMessage("earth2star", null);
			gameObject.SetActive(false);
		}
	}
}
